//index.js
//获取应用实例
const http = require('../../utils/http.js');
const app = getApp();
var regeneratorRuntime = require("../../utils/regenerator-runtime/runtime.js");
const { $Toast } = require('../../dist/base/index');
Page({


  data: {
    spinShow: true,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    imgUrls: [],
    isHidden: false,
    navArr: [{
        name: '取快递',
        icon: '../images/nav3.png'
      },
      {
        name: '寄快递',
        icon: '../images/nav2.png'
      },
      {
        name: '帮跑腿',
        icon: '../images/nav1.png'
      },

    ],
    robList: []
  },
//获取轮播图
getBnaner(){
  var sid = wx.getStorageSync('nowSchool').id
  http.fetchApi('procedure_t', {p: 'R2007010|' + sid+'|1'}).then(res=>{
    if(res.data.code==1){
      var imgUrls = res.data.results;
      this.setData({
        imgUrls
      })
    }
  })
},
//轮播图链接商详情
  toShopDetail(e){
    var good_id = e.currentTarget.dataset.id;
    console.log(good_id);
    if (good_id==undefined){
     wx.switchTab({
       url: '../FlashDelivery/FlashDelivery',
     })
    }else{
      wx.switchTab({
        url: '../FlashDelivery/FlashDelivery',
        success: () => {

          setTimeout(() => {
            wx.navigateTo({
              url: '../goodsDetail/goodsDetail?gid=' + good_id,
            })
          }, 500)
        }
      })
    }
   
  },

  //获取首页的三张链接图
  getPageImg(){
    http.fetchApi('procedure_t', {
      p: 'R2007011|'
    })
  },
  //nav跳转
  toPage(e) {
    var id = e.currentTarget.dataset.id
    switch (id) {
      //取快递页面
      case 0:
        wx.navigateTo({
          url: '../takeExpress/takeExpress?takeType=0',
        })
        break;
        //寄快递页面
      case 1:
        wx.navigateTo({
          url: '../takeExpress/takeExpress?takeType=1',
        })
        break;
        //帮跑腿页面
      case 2:
        wx.navigateTo({
          url: '../takeExpress/takeExpress?takeType=2',
        })
        break;
    }
  },

  //跳转排行榜页面
  toRank() {
    wx.navigateTo({
      url: '../ranking/ranking',
    })
  },

  //跳转接单详情
  goldDetail(e) {
    if (app.globalData.renzheng==0){
      wx.showModal({
        title: '提示',
        content: '您还不是骑手,是否去认证?',
        success(res) {
          if (res.confirm) {
           wx.navigateTo({
             url: '../certifiedRider/certifiedRider',
           })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })

      return
    }else{
      var oid = e.currentTarget.dataset.oid
      wx.navigateTo({
        url: '../receiptDetail/receiptDetail?oid=' + oid,
      })
    }
   
  },

  //骑手认证
  toRenzheng() {
    if (app.globalData.renzheng == 0){
      wx.navigateTo({
        url: '../certifiedRider/certifiedRider',
      })
    }else{
      $Toast({
        content: '您已经是骑手了!',
        type: 'error'
      });
    }
   
  },

  //跳转闪送超市
  toShop() {
    wx.switchTab({
      url: '../FlashDelivery/FlashDelivery',
    })
  },

  //跳转红包页面
  toHongbao(){
    wx.navigateTo({
      url: '/pages/couponCenter/couponCenter',
    })
  },

  //跳转我的订单
  toMyOrder() {
    wx.navigateTo({
      url: '../MoreOrder/MoreOrder',
    })
  },
  //抢单
  grabOrder(e) {
    var formId = e.detail.formId;
    var uid = app.globalData.uid;
    var oid = e.target.dataset.oid;
    console.log('R2013001|' + formId + '|' + uid)
    http.fetchApi('procedure_t', {
      p: 'R2013001|' + formId + '|' + uid
    })
    if (app.globalData.renzheng == 0){
      
      $Toast({
        content: '您还不是骑手,无法抢单!',
        type: 'error'
      });
      return
    }
    

 
    http.fetchApi('p_order_qd', {
      p: 'R2002001|' + uid + '|' + oid
    }).then(res => {
      if (res.data.code == 1) {
        var codes = res.data.results[0].codes;
        this.setData({
          codes
        })

        if (codes == 1) {
          //抢单成功
         // http.showToast('抢单成功!' + '', '', '')
          $Toast({
            content: '您已成功抢到订单!',
            type: 'success'
          });
            setTimeout(() => {
              wx.reLaunch({
                url: '../index/index'
              })
            }, 800)
          
        } else if (codes == 0){
          $Toast({
            content: '抢单失败!',
            type: 'error'
          });
        } else if (codes == 3) {
          $Toast({
            content: '您暂无抢单权限!',
            type: 'error'
          });
          //http.showToast('您暂无抢单权限!' + '', '', 'none')
        } else if (codes == 2) {
         // http.showToast('您还不是骑手!' + '', '', 'none')
          $Toast({
            content: '您还不是骑手!',
            type: 'error'
          });
        } else if (codes == 4) {
          $Toast({
            content: '您不能抢自己的单!',
            type: 'error'
          });
         // http.showToast('您不能抢自己的单!' + '', '', 'none')
        }
      } else{
        $Toast({
          content: '抢单失败!',
          type: 'error'
        });
      }
    })
  },

  //获取首页订单列表
  getOrderList(e) {
  //  wx.showLoading({
  //    title: '加载中...',
  //  })
    var page = e.detail || e
    var params = {
      p: 'R1001001',
      k: page,
      j: 100,
      cs: wx.getStorageSync('nowSchool').id
    }
    http.fetchApi('procedureList', params).then(res => {

      if (res.data.code == 1) {
        // wx.hideLoading()
        wx.stopPullDownRefresh();
        this.getBnaner()
        var robList = this.data.robList;
        if(page==1){
          robList=[]
        }
        var robList1 = res.data.results;
        // console.log(res.data.results);
        if (robList1.length == 0 && page > 1) {
          // http.showToast('再拉也没有啦!' + '', '', 'none')
          return
        }
        robList = [...robList, ...robList1]
        this.setData({
          robList,
          page
        })
      } else {
        $Toast({
          content: '获取列表失败!',
          type: 'error'
        });
      }

    })

  },

  emptyList() {
    this.setData({
      robList: []
    })
  },

 getUserInfor() {
   
    // 获取用户信息
    wx.getSetting({
      
      success: res => {
        wx.hideLoading();
        //console.log(app.globalData.uid)
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框

          wx.getUserInfo({
            success: res => {
             // console.log(res)
              //console.log(res)
              // 可以将 res 发送给后台解码出 unionId
              app.globalData.userInfo = res.userInfo
              console.log(app.globalData.userInfo);

              //防止多次登录
             // this.login(res)
             !app.globalData.uid ? this.login(res) : ""
            }
          })
        }else{
          this.setData({
            isHidden: true,
          })
        }
      }
    })


  },

  //授权回调
  toAuthorize(e) {
    console.log(e)
    if (e.detail.errMsg == 'getUserInfo:ok'){
      this.setData({
        isHidden: false
      })
      wx.reLaunch({
        url: '../index/index?scene=' + this.data.xid
      })
    }else{
      return
    }
   
  },

  cancel() {
    this.setData({
      isHidden: false
    })
  },
  emoji2Str(str) {

    return unescape(escape(str).replace(/\%uD.{3}/g, ''));

  },
  
  
  //登录
  login(results) {
    wx.showLoading({
      title: '获取用户信息...',
    })
    var that = this
    wx.login({
      success:(res)=> {
        
        if (res.code) {
          var url;
          const yxhj = wx.getSystemInfoSync();
          console.log(yxhj.AppPlatform)
          app.globalData.cj = yxhj.AppPlatform
          if (yxhj.AppPlatform=='qq'){
            url = app.globalData.host + 'qqApi/login'
          }else{
            url = app.globalData.host + 'api/login'
          }
          wx.request({
            url,
            method: 'get',
            header: {
              "Content-Type": "applciation/json"
            },
            // data: { encryptedData: results.encryptedData, iv: results.iv, code: res.code },
            data: { avatarUrl: results.userInfo.avatarUrl, nickName: this.emoji2Str(results.userInfo.nickName)  , code: res.code },
            success: (result)=> {
              
              if(result.data.code==1){      
                wx.hideLoading();
                
                //获取首页三图
               // this.getPageImg();
               
                //校区跑腿费
                this.getPlatformFee();
                //token保存全局
                app.globalData.token = result.data.accesstoken;
                //uid保存全局
                app.globalData.uid = result.data.uid;

                //获取子组件
                var location = that.selectComponent('#location');
                console.log(location)
                that.setData({
                  location
                })

                //用户身份
                app.globalData.renzheng = result.data.renzheng;
               // location.getShoolList();
                location.getLocation()
                //绑定下级
                if (this.data.xid!=undefined){
                  console.log('已经准备就绪开始绑定下级uid' + this.data.xid)
                  var uid = app.globalData.uid;
                   var xid = this.data.xid;
                  console.log('开始绑定下级' + 'R2010005|' + uid + '|' + xid)
                  //http.fetchApi('procedure_t', { p: 'R2010005|' + uid+'|'+xid })

                  wx.request({
                    url: app.globalData.host + 'procedure_t',
                    method: 'post',
                    header: {
                      "Content-Type": "application/x-www-form-urlencoded"
                    },
                    data: { p: 'R2010005|' + result.data.uid + '|' + xid },
                    success: (result) => {

                    }
                    })
                }

                // that.getOrderList(1)
                // console.log(that.data.location)
                that.setData({
                  renzheng: result.data.renzheng
                })
              }else{
        
                $Toast({
                  content: '登陆失败',
                  type: 'error'
                });
              }
                   
            }
          })
           

        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })


  },
  //获取去送快递跑腿费
  getPlatformFee() {
    var school_id = wx.getStorageSync('nowSchool').id;
    http.fetchApi('procedure_t', { p: 'R2012002|' + school_id }).then(res => {
      if (res.data.code == 1) {
        var platformFeer = res.data.results[0].ptf;
        app.globalData.platformFeer = platformFeer;
      }
    })
  },

  //跳转签到页面
  toSignIn(){
    wx.navigateTo({
      url: "../signIn/signIn"
    })
  },

  
  
   onLoad: function (options) {
  //  constres = wx.getSystemInfoSync();
    //二维码参数
     console.log('二维码参数:' + options.scene, typeof(options.scene) )

     app.globalData.xid = options.scene
    if (options.scene!='undefined'){
      this.setData({
        xid: options.scene
      })
    }
    
   this.getUserInfor();
    
    wx.removeStorageSync('totalPrice');
    wx.removeStorageSync('jiadanId');
    wx.removeStorageSync('hongbao');
    console.log(app.globalData.uid)
    
  },
  onReady: function() {

  },
  onShow: function() {

  },
  
  //下拉刷新
  onPullDownRefresh:function(){
    this.getOrderList(1)
  },

  onReachBottom: function() {
    var page = this.data.page || 1;
    page++;
    this.getOrderList(page);
  },
  onHide() {

  },

  // onTabItemTap(item) {
  //   console.log(item.index)
  //   console.log(item.pagePath)
  //   console.log(item.text)
  // },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }


})